package com.ilia.slitok;

import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.ConcurrentSkipListSet;

import com.ilia.util.timer.ITimer;

public class PolyAlloyStorageSortedSetImpl implements PolyAlloyStorage {
  
  private ConcurrentSkipListSet<PolyAlloy>  storage;
  ITimer timer;
  private PolyAlloyTargetAlloyComparator comparator;
  
  public PolyAlloyStorageSortedSetImpl(ITimer timer, int[] target_coord) {
    comparator = new PolyAlloyTargetAlloyComparator(target_coord);
    storage = new ConcurrentSkipListSet<PolyAlloy>(comparator);
    this.timer = timer;
  }
  
  
  public ConcurrentSkipListSet<PolyAlloy> createNewStorage() {
    ConcurrentSkipListSet<PolyAlloy> st = new ConcurrentSkipListSet<PolyAlloy>(comparator);
    return st;
  }
  public void setStorage(ConcurrentSkipListSet<PolyAlloy> storage) {
    this.storage = storage;
    
  }
  public ConcurrentSkipListSet<PolyAlloy> getStorage() {return storage;}
  
  public String toString() {
    return "Sorted storage: "+storage.size()+" items";
  }
  public PolyAlloy get(PolyAlloy pa) {
    timer.startTimer("PASS_GET");
    PolyAlloy r = null;
    if (storage.contains(pa)) {
      r = storage.floor(pa);
    }
    timer.stopTimer("PASS_GET");
    return r;
  }
  
  public void add(PolyAlloy pa) {
    timer.startTimer("PASS_ADD");
    PolyAlloy ex = get(pa);
    if (ex==null) {
      storage.add(pa);
    } else {
      ex.getAlloys().addAll(pa.getAlloys());
    }
    timer.stopTimer("PASS_ADD");
  }

  
  public Collection<PolyAlloy> values() {
    return storage;
  }
  
  public int getSize() { 
    return storage.size();
  }
  
  public void trunc_and_pack(int new_size, boolean pack) {
    timer.startTimer("KILLBAD");
    ConcurrentSkipListSet<PolyAlloy> set = getStorage();
    ConcurrentSkipListSet<PolyAlloy> newset = createNewStorage();
    int cnt = 0;
    Iterator<PolyAlloy> iter = set.iterator();
    while (cnt < new_size) {
      PolyAlloy next = iter.next();
      if (pack) {
        next.pack();
      }
      newset.add(next);
      cnt++;
    }
    setStorage(newset);
    timer.stopTimer("KILLBAD");
  }


  public Collection<PolyAlloy> sorted_values(int max_count) {
    return storage;
  }


}
